<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ taglib prefix="d" uri="http://dgg.net/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title></title>
    <c:import url="../../header.jsp"/>
</head>
<body>
<div class="content-warp pb50">
    <div class="bg-warp">
        <!--商机信息 start-->
        <div class="dggui-panel">
            <h3>商机信息</h3>
            <input type="hidden" id="orderNo" value="${order.orderNo}">
            <input type="hidden" id="contractNo" value="${order.contractNo}">
            <table class="dggui-table-info">
                <tbody>
                <tr>
                    <th>商机编号：</th>
                    <td>${order.businessNo}</td>
                    <th>业态：</th>
                    <td>${order.businessTypeName}</td>
                    <th>联系方式：</th>
                    <td>${order.contactPhone}</td>
                </tr>
                <tr>
                    <th>商机跟进人：</th>
                    <td>${order.signUserName}</td>
                    <th></th>
                    <td></td>
                    <th></th>
                    <td></td>
                </tr>
                </tbody>
            </table>
        </div>
        <!--商机信息 end-->
        <!--客户信息 start-->
        <form id="customerJson">
            <div class="dggui-panel">
            <h3>客户信息</h3>
            <table class="dggui-table-info">
                <tbody>
                <tr>
                    <th><span class="required">客户名称：</span></th>
                    <td>
                        <input type="hidden" id="customerId" name="customerId" value="${order.customerId}">
                        <input type="hidden" id="customerNo" name="customerNo" value="${order.customerNo}">
                        <input require="true" message="不能为空" maxLength="50" methods="isNonEmpty" type="text" name="customerName" id="customerName" class="dggui-input" value="${order.customerName}" onchange="changeCustomerName(this,1);">
                    </td>
                    <th>客户电话：</th>
                    <td><input type="hidden" name="customerPhone" id="customerPhone" class="dggui-input" value="${customerPhone}">${order.contactPhone}</td>
                    <th><span class="required">身份证号：</span></th>
                    <td><input require="true" message="请输入正确的身份证号" maxLength="50" methods="isNonEmpty,;isRegExp:^[A-Za-z0-9]+$" type="text" class="dggui-input" name="idCard" value="${customerDTO.idCard}" onchange="idCardChange($(this),1);" id="idCard"></td>
                </tr>
                <tr>
                    <th><span class="required">客户性别：</span></th>
                    <td>
                        <select require="true" message="不能为空" methods="isNonEmpty" class="dggui-select" name="sex" id="sex">
                        </select>
                    </td>
                    <th><span class="required">客户年龄：</span></th>
                    <td><input require="true" message="请输入正确的客户年龄" maxLength="3" methods="isNonEmpty ,; isIntGte:0" type="text" class="dggui-input" name="age" id="age" value="${customerDTO.age}"></td>
                    <th><span class="required">生日：</span></th>
                    <td><input require="true" message="不能为空" methods="isNonEmpty" type="text" class="dggui-input" name="birthday" id="birthday" value="${customerDTO.birthday}"></td>
                </tr>
                <tr>
                    <th><span class="required">户口所在地：</span></th>
                    <td><input require="true" message="不能为空" maxLength="150" methods="isNonEmpty" type="text" class="dggui-input" name="registeredResidence" id="registeredResidence" value="${customerDTO.houseRegister}"></td>
                    <th><span class="required">客户学历：</span></th>
                    <td>
                        <select require="true" message="不能为空" methods="isNonEmpty"  class="dggui-select" name="eduBackground" id="eduBackground">
                        </select>
                    </td>
                    <th><span class="required">客户婚姻状况：</span> </th>
                    <td>
                        <select require="true" message="不能为空" methods="isNonEmpty"  class="dggui-select" name="maritalStatus" id="maritalStatus" onchange="changeMaritalStatus(this,1);">
                        </select>
                    </td>
                </tr>
                <tr>
                    <th><span class="required">客户子女个数：</span></th>
                    <td><input require="true" message="请输入0-999以内数字" methods="isNonEmpty ,; isIntGte:0 ,; isInterval:0:999" type="number" max="999" min="0" class="dggui-input" name="childrenNum" id="childrenNum" value="${customerDTO.childrens}" onchange="changeChildrenNum(this,1);"></td>
                    <th><span class="required">客户地址：</span></th>
                    <td><input type="text" require="true" message="不能为空" maxLength="150" methods="isNonEmpty"  class="dggui-input" name="address" id="address" value="${customerDTO.address}"></td>
                    <th>邮箱：</th>
                    <td><input require="true" message="请输入正确的邮箱地址" maxLength="50" methods="isEmail" type="text" class="dggui-input" name="email" id="email"></td>
                </tr>
                </tbody>
            </table>
        </div>
        </form>
        <!--客户信息 end-->
        <!--借贷人 start-->
        <form id="concactForm">
            <div class="dggui-panel">
            <h3>借贷人
            </h3>
            <table class="dggui-table cell-border table-form" id="loansTable">
                <thead>
                <th><span class="red">*</span>姓名</th>
                <th><span class="red">*</span>身份</th>
                <th><span class="red">*</span>是否是客户本人</th>
                <th><span class="red">*</span>身份证号码</th>
                <th><span class="red">*</span>联系方式</th>
                <th><span class="red">*</span>婚姻状况</th>
                <th><span class="red">*</span>子女情况</th>
                <th><span class="red">*</span>家属是否知晓</th>
                <th><span class="red">*</span>与借贷人关系</th>
                <th>操作</th>
                </thead>
                <tbody>
                <tr>
                    <td><input require="true" message="不能为空" maxLength="50" methods="isNonEmpty" type="text" class="dggui-input" name="name" onchange="changeCustomerName(this,2);"></td>
                    <td>
                        <select require="true" message="不能为空" methods="isNonEmpty" class="dggui-select" name="lenderStatus" onchange="changeState(this,1);">
                            <option value="">请选择</option>
                            <option value="0">主借贷人</option>
                            <option value="1">次借贷人</option>
                        </select>
                    </td>
                    <td>
                        <select  require="true" message="不能为空" methods="isNonEmpty"  class="dggui-select" name="isSelf" onchange="getCustomerMessage(this);">
                            <option value="">请选择</option>
                            <option value="1">是</option>
                            <option value="0">否</option>
                        </select>
                    </td>
                    <td><input require="true" message="请输入正确的身份证号" maxLength="50" methods="isNonEmpty ,; isRegExp:^[A-Za-z0-9]+$" type="text" class="dggui-input" name="cardId"></td>
                    <td><input require="true" message="请输入正确的电话号码" methods="isNonEmpty ,; isPhone" type="text" class="dggui-input" name="no"></td>
                    <td>
                        <select  require="true" message="不能为空" methods="isNonEmpty" class="dggui-select" name="contactMaritalStatus" onchange="changeMaritalStatus(this,2);">
                        </select>
                    </td>
                    <td><input require="true" message="请输入0-999以内数字" methods="isNonEmpty ,; isIntGte:0 ,; isInterval:0:999" type="number" max="999" min="0" class="dggui-input" name="contactChildrenNum" onchange="changeChildrenNum(this,2);"></td>
                    <td>
                        <select  require="true" message="不能为空" methods="isNonEmpty" class="dggui-select" name="noKnow">
                            <option value="">请选择</option>
                            <option value="1">知晓</option>
                            <option value="0">不知晓</option>
                        </select>
                    </td>
                    <td>
                        <select  require="true" message="不能为空" methods="isNonEmpty" class="dggui-select" name="relationshipOfCus" onchange="changeState(this,2);">
                        </select>
                    </td>
                    <td>
                        <%--<a href="javascript:void(0)" class="dggui-icon-btn" onclick="removeTrRow(this)" title="删除"><i class="iconfont icon-shanchu"></i></a>--%>
                    </td>
                </tr>
                <tr>
                    <td colspan="10" class="txt-center">
                        <a href="javascript:void(0)" class="dggui-link dggui-icon-btn" onclick="addRow(this)"><i class="iconfont icon-tianjia"></i><span>新增借贷人</span></a>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        </form>
        <!--借贷人 end-->
        <!--合同约定 start-->
            <div class="dggui-panel">
            <h3>合同约定</h3>
                <form id="contractForm">
                    <table class="dggui-table-info">
                <tbody>
                <tr>
                    <th><span class="required">需求总金额：</span></th>
                    <td>
                        <div class="unit-warp">
                            <input require="true" message="请输入正确的数字" methods="isNonEmpty,;isRegExp:^\d+(\.\d+)?$" type="text" class="dggui-input"  oninput="calcContractMoneyF(this);"  maxlength="12" value="${order.amount}" name="loansAmount" id="loansAmount">
                            <span class="unit">元</span>
                        </div>
                    </td>
                    <th><span class="required">贷款年限：</span></th>
                    <td>
                        <div class="units-warp" style="max-width: 100%">
                            <input require="true" message="请输入正确的数字" methods="isNonEmpty,;isRegExp:^\d+(\.\d+)?$"  type="text" class="dggui-input" name="loansNum" id="loansNum" oninput="calcContractMoneyF(this);" >
                            年

                            <select require="true" message="不能为空" methods="isNonEmpty" class="dggui-select" name="loansRateType" id="loansRateType" style="width: 100px">
                            </select>
                        </div>
                    </td>
                    <th><span class="required">贷款利息：</span></th>
                    <td>
                        <div class="unit-warp">
                            <input require="true" message="请输入正确的数字" methods="isNonEmpty,;isRegExp:^\d+(\.\d+)?$" type="text" oninput="calcContractMoneyF(this,12);"  maxlength="12" class="dggui-input" name="loansInterest" id="loansInterest">
                            <span class="unit">%</span>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th><span class="required">定金：</span></th>
                    <td>
                        <div class="unit-warp">
                            <input require="true" message="请输入正确的数字" value="0" methods="isNonEmpty,;isRegExp:^\d+(\.\d+)?$" type="text" oninput="calcContractMoneyF(this,12);" maxlength="12" class="dggui-input" name="earnestMoney" id="earnestMoney">
                            <span class="unit">元</span>
                        </div>
                    </td>
                    <th></th>
                    <td></td>
                    <th></th>
                    <td></td>
                </tr>
            </table>
                </form>
            <hr>
            <h4>办理业务</h4>
                <form id="businessForm">
                    <table class="dggui-table cell-border table-form">
                        <thead>
                        <th>业务类型</th>
                        <th>产品</th>
                        <th>商品属性</th>
                        <th><span class="red">*</span> 手续费（%）</th>
                        <th><span class="red">*</span>利率方式</th>
                        <th><span class="red">*</span> 需求金额（元）</th>
                        <th>合同编号</th>
                        <th><span class="red">*</span> 建议渠道</th>
                        <th><span class="red">*</span> 流程人员</th>
                        <th>事业部</th>
                        </thead>
                        <tbody>
                        <c:forEach var="key" items="${products}">
                            <tr>
                                <td>
                                    <input type="hidden" name="orderBusId" value="${key.orderBusId}">
                                    <input type="hidden" name="orderBusNo" value="${key.orderBusNo}">
                                    <input type="hidden" name="productOrgId" value="${key.productOrgId}">
                                    <input type="hidden" name="productOrgName" value="${key.productOrgName}">
                                    <input type="hidden" name="businessTypeCode" value="${key.businessTypeId}">
                                    <input type="hidden" name="businessTypeName" value="${key.businessTypeName}">
                                    <input type="hidden" name="businessProductCode" value="${key.businessProductId}">
                                    <input type="hidden" name="businessProductName" value="${key.businessProductName}">
                                    <input type="hidden" name="productId" value="${key.productId}">
                                    <input type="hidden" name="productName" value="${key.productName}">
                                    <input type="hidden" name="contractNo" value="${key.contractNo}">
                                    <input type="hidden" name="productGoodsId" value="${key.productGoodsId}">
                                    <input type="hidden" name="productAttr" value="${key.productAttr}">

                                ${key.businessProductName}
                                </td>
                                <td>${key.productName}</td>
                                <td>${key.productAttr}</td>
                                <td> <input require="true" message="请输入正确的数字" methods="isNonEmpty,;isRegExp:^\d+(\.\d+)?$" type="text" oninput="calcContractMoneyF(this,12);" maxlength="12" class="dggui-input" name="serviceCharge"></td>
                                <td>
                                    <div class="unit-warp">
                                        <select require="true" message="不能为空" methods="isNonEmpty" class="dggui-select" name="rateType">
                                        </select>
                                    </div>
                                </td>
                                <td>
                                    <div class="unit-warp">
                                        <input require="true" message="请输入正确的数字" methods="isNonEmpty,;isRegExp:^\d+(\.\d+)?$"  type="text" oninput="calcContractMoneyF(this,12);"  maxlength="12" class="dggui-input" name="loanAmount">
                                    </div>
                                </td>
                                <td>${order.contractNo}</td>
                                <td>
                                    <select require="true" message="不能为空" methods="isNonEmpty"  class="dggui-select" name="channelId">
                                    </select>
                                </td>
                                <td>
                                    <select class="dggui-select" name="flowUserId" require="true"  message="不能为空" methods="isNonEmpty">
                                    </select>
                                </td>
                                <td>
                                    ${key.productOrgName}
                                </td>
                            </tr>
                        </c:forEach>
                        </tbody>
                    </table>
                </form>
            <div class="textarea-warp">
                <textarea class="dggui-textarea" name="mortgageAddress" id="mortgageAddress" rows="2" maxlength="150" placeholder="请输入抵押物地址"></textarea>
            </div>
        </div>
        <!--合同约定 end-->
        <!--成本费 start-->
        <div class="dggui-panel">
            <h3>成本费</h3>
            <form id="subjectForm">
                <table class="dggui-table cell-border table-form">
                    <thead>
                    <th>科目</th>
                    <th>数量</th>
                    <th>价格</th>
                    <th>操作</th>
                    </thead>
                    <tbody>
                    <tr>
                        <td>
                            <select class="dggui-select" name="subjectType">
                            </select>
                        </td>
                        <td>
                            <input type="text" oninput="calcContractMoneyF(this,12);"   maxlength="12" class="dggui-input" name="subjectNum">
                        </td>
                        <td>
                            <div class="unit-warp">
                                <input type="text" oninput="calcContractMoneyF(this,12);"  maxlength="12" class="dggui-input" name="subjectAmount">
                                <span class="unit">元</span>
                            </div>
                        </td>
                        <td>
                            <%--<a href="javascript:void(0)" class="dggui-icon-btn" onclick="removeTrRow(this)" title="删除"><i class="iconfont icon-shanchu"></i></a>--%>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="4" class="txt-center">
                            <a href="javascript:void(0)" class="dggui-link dggui-icon-btn" onclick="addMoneyRow(this)"><i class="iconfont icon-tianjia"></i><span>新增费用项目</span></a>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </form>
        </div>
        <!--成本费 end-->
    </div>
    <div class="txt-center fix-btn-warp">
        <button class="dggui-btn" onclick="saveUnderOrder();">提交审核</button>
    </div>
</div>

</body>
<c:import url="/WEB-INF/jsp/footer.jsp"/>
<script>
    dggui.use(['select2','dggdate'],function () {
        var select2 = dggui.select2;
        var dggdate = dggui.dggdate;
        //初始化性别状态
        commonTreeBookCode("#sex", "CMS_SEX", 1, 1, 1, true,'${customerDTO.sex}');
        //初始化生日
        dggdate.render({
            elem: '#birthday',
            type: 'date'
        });
        //初始化学历
        commonTreeBookCode("#eduBackground", "KHXL", 1, 1, 1, true,'${customerDTO.education}');
        //初始化婚姻状况
        commonTreeBookCode("#maritalStatus", "HYZK", 1, 1, 1, true,'${customerDTO.maritalStatus}');
        //初始化婚姻状况
        commonTreeBookCode("[name='contactMaritalStatus']", "HYZK", 1, 1, 1, true);
        //与借贷人关系
        commonTreeBookCode("[name='relationshipOfCus']", "ORF_JDRGX", 1, 1, 1, true);

        //利率方式
        commonTreeBookCode("#loansRateType", "ORF_LLFS", 1, 1, 1, true);
        commonTreeBookCode("[name='rateType']", "ORF_LLFS", 1, 1, 1, true);
        //初始化科目
        commonTreeBookCode("[name='subjectType']", "ORF_KEMU", 1, 1, 1, true);

        $.each($("[name='flowUserId']"),function (i,v) {
            //初始化流程人员
            initUser("RZSC_FLOW_USER","role",this,$(this).parents("tr").find("[name='productOrgId']").val());
            select2.render({
                placeholder: "请选择",
                allowClear: true,
                elem: $("[name='flowUserId']"),
                width:"100%"
            });
        });
        //初始化渠道
        $.each($("[name='channelId']"),function (i,v) {
            //initChannelWithCode(this,$(this).parents("tr").find("[name='productGoodsId']").val());
            initChannel(this,$(this).parents("tr").find("[name='productId']").val());
            select2.render({
                placeholder: "请选择",
                allowClear: true,
                elem: $(this),
                width:"100%"
            });
        });
    });

    /**
     * 新增借贷人
     * @param obj
     */
    function addRow(obj) {
        var rows = $("[name='lenderStatus']");
        if(rows.length>=5){
            dggui.dialog.info("最多增加5个借贷人！");
            return;
        }
        var trHtm='<tr>' +
            '<td><input require="true" message="不能为空" maxLength="50" methods="isNonEmpty" type="text" class="dggui-input" name="name" onchange="changeCustomerName(this,2);"></td>' +
            '<td>' +
            '<select require="true" message="不能为空" methods="isNonEmpty"  class="dggui-select" name="lenderStatus" onchange="changeState(this,1);">' +
            '<option value="">请选择</option>' +
            '<option value="0">主借贷人</option>' +
            '<option value="1">次借贷人</option>' +
            '</select>' +
            '</td>' +
            '<td>' +
            '<select  require="true" message="不能为空" methods="isNonEmpty" class="dggui-select" name="isSelf" onchange="getCustomerMessage(this);">' +
            '<option value="">请选择</option>' +
            '<option value="1">是</option>' +
            '<option value="0">否</option>' +
            '</select>' +
            '</td>' +
            '<td><input require="true" message="请输入正确的身份证号" maxLength="50" methods="isNonEmpty ,; isRegExp:^[A-Za-z0-9]+$" type="text" class="dggui-input" name="cardId"></td>' +
            '<td><input require="true" message="请输入正确的电话号码" methods="isNonEmpty ,; isPhone" type="text" class="dggui-input" name="no"></td>' +
            '<td>' +
            '<select require="true" message="不能为空" methods="isNonEmpty" class="dggui-select" name="contactMaritalStatus" onchange="changeMaritalStatus(this,2);">' +
            '</select>' +
            '</td>' +
            '<td><input require="true" message="请输入0-999以内数字" methods="isNonEmpty ,; isIntGte:0 ,; isInterval:0:999" type="number" max="999" min="0" class="dggui-input" name="contactChildrenNum" onchange="changeChildrenNum(this,2);"></td>' +
            '<td>' +
            '<select  require="true" message="不能为空" methods="isNonEmpty" class="dggui-select"  name="noKnow">' +
            '<option value="">请选择</option>' +
            '<option value="1">知晓</option>' +
            '<option value="0">不知晓</option>' +
            '</select>' +
            '</td>' +
            '<td>' +
            '<select  require="true" message="不能为空" methods="isNonEmpty" class="dggui-select" name="relationshipOfCus" onchange="changeState(this,2);">' +
            '</select>' +
            '</td>' +
            '<td>' +
            '<a href="javascript:void(0)" class="dggui-icon-btn" onclick="removeTrRow(this)" title="删除"><i class="iconfont icon-shanchu"></i></a>' +
            '</td>' +
            '</tr>';
        $(obj).parents('tr').before(trHtm);

        //初始化婚姻状况
        var domMarital = $(obj).parents('tr').prev().find("[name='contactMaritalStatus']");
        commonTreeBookCodeUnder(domMarital, "HYZK", 1, 1, 1, true);
        //与借贷人关系
        var domOfCus= $(obj).parents('tr').prev().find("[name='relationshipOfCus']");
        commonTreeBookCodeUnder(domOfCus, "ORF_JDRGX", 1, 1, 1, true);
    }

    /**
     * 增加科目
     * */
    function addMoneyRow(obj) {
        var rows = $("[name='subjectType']");
        if(rows.length>=10){
            dggui.dialog.info("最多增加10条成本费！");
            return;
        }
        var trHtm='<tr>' +
            '<td><select class="dggui-select" name="subjectType"></select></td>' +
            '<td>' +
            '<input type="text" oninput="calcContractMoneyF(this,12);" maxlength="12" class="dggui-input" name="subjectNum">' +
            '</td>' +
            '<td>' +
            '<div class="unit-warp">' +
            '<input type="text" oninput="calcContractMoneyF(this,12);" maxlength="12" class="dggui-input" name="subjectAmount">' +
            '<span class="unit">元</span>' +
            '</div>' +
            '</td>' +
            '<td><a href="javascript:void(0)" class="dggui-icon-btn" onclick="removeTrRow(this)" title="删除"><i class="iconfont icon-shanchu"></i></a></td>' +
            '</tr>';
        $(obj).parents('tr').before(trHtm);
        //初始化科目
        var domSubject= $(obj).parents('tr').prev().find("[name='subjectType']");
        commonTreeBookCode(domSubject, "ORF_KEMU", 1, 1, 1, true);
    }

    /**
     * 移除一行
     * @param obj
     */
    function removeTrRow(obj) {
        $(obj).parents('tr').remove();
    }


    /**
     * 提交审核
     */
    function saveUnderOrder() {

       //验证客户信息
       var customerNameCheck = verifyEmpty($("#customerName"),"不能为空") && verifyLength($("#customerName"),50,"最多50个字符");
       var idCardCheck = verifyEmpty($("#idCard"),"请输入正确的身份证号") && isIdCard($("#idCard"),"请输入正确的身份证号")&& verifyLength($("#idCard"),50,"最多50个字符");
       var sexCheck = verifyEmpty($("#sex"),"不能为空");
       var ageCheck = verifyEmpty($("#age"),"请输入正确的客户年龄")&&isIntNumberTip($("#age"),"请输入正确的客户年龄！")&&ageCheckTip($("#age"),"年龄不能超过999");
       var birthdayCheck = verifyEmpty($("#birthday"),"不能为空");
       var registeredResidenceCheck = verifyEmpty($("#registeredResidence"),"不能为空") && verifyLength($("#registeredResidence"),150,"最多150个字符");
       var eduBackgroundCheck = verifyEmpty($("#eduBackground"),"不能为空");
       var maritalStatusCheck = verifyEmpty($("#maritalStatus"),"不能为空");
       var childrenNumCheck = verifyEmpty($("#childrenNum"),"请输入0-999以内数字")&&isIntNumberTip($("#childrenNum"),"请输入0-999以内数字！")&&ageCheckTip($("#childrenNum"),"请输入0-999以内数字");
       var addressCheck = verifyEmpty($("#address"),"不能为空") && verifyLength($("#address"),150,"最多150个字符");

       var emailCheck = true;
       if(checkEmpty($("#email").val())){
           emailCheck = isEMail($("#email"),"请输入正确的邮箱地址");
       }

       //验证借贷人信息
        var nameCheck = false;
        $.each($("[name='name']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"不能为空") && verifyLength($(this),50,"最多50个字符");
            if(!nCheck){
                nameCheck = false;
                return false;
            }else{
                nameCheck = true;
            }
        });

        var lenderStatusCheck = false;
        $.each($("[name='lenderStatus']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"不能为空");
            if(!nCheck){
                lenderStatusCheck = false;
                return false;
            }else{
                lenderStatusCheck = true;
            }
        });

        var isSelfCheck = false;
        $.each($("[name='isSelf']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"不能为空");
            if(!nCheck){
                isSelfCheck = false;
                return false;
            }else{
                isSelfCheck = true;
            }
        });

        var cardIdCheck = false;
        $.each($("[name='cardId']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"请输入正确的身份证号") && isIdCard($(this),"请输入正确的身份证号") && verifyLength($(this),50,"50个字符以内");
            if(!nCheck){
                cardIdCheck = false;
                return false;
            }else{
                cardIdCheck = true;
            }
        });

        var noCheck = false;
        $.each($("[name='no']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"请输入正确的电话号码") && isTel($(this),"请输入正确的电话号码");
            if(!nCheck){
                noCheck = false;
                return false;
            }else{
                noCheck = true;
            }
        });

        var contactMaritalStatusCheck = false;
        $.each($("[name='contactMaritalStatus']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"不能为空");
            if(!nCheck){
                contactMaritalStatusCheck = false;
                return false;
            }else{
                contactMaritalStatusCheck = true;
            }
        });

        var contactChildrenNumCheck = false;
        $.each($("[name='contactChildrenNum']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"请输入0-999以内数字")&&isIntNumberTip($(this),"请输入0-999以内数字！")&&ageCheckTip($(this),"请输入0-999以内数字");
            if(!nCheck){
                contactChildrenNumCheck = false;
                return false;
            }else{
                contactChildrenNumCheck = true;
            }
        });

        var noKnowCheck = false;
        $.each($("[name='noKnow']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"不能为空");
            if(!nCheck){
                noKnowCheck = false;
                return false;
            }else{
                noKnowCheck = true;
            }
        });

        var relationshipOfCusCheck = false;
        $.each($("[name='relationshipOfCus']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"不能为空");
            if(!nCheck){
                relationshipOfCusCheck = false;
                return false;
            }else{
                relationshipOfCusCheck = true;
            }
        });


        //验证合同约定
        var loansAmountCheck = verifyEmpty($("#loansAmount"),"请输入正确的数字") && isNumberTip($("#loansAmount"),"请输入正确的数字","金额不能超过99999999999");
        var loansNumCheck = verifyEmpty($("#loansNum"),"请输入正确的数字") && isNumberTip($("#loansNum"),"请输入正确的数字","年限不能超过99999999999");
        var loansInterestCheck = verifyEmpty($("#loansInterest"),"请输入正确的数字") && isNumberTip($("#loansInterest"),"请输入正确的数字","利息不能超过99999999999");
        var loansRateTypeCheck = verifyEmpty($("#loansRateType"),"不能为空");
        var earnestMoneyCheck = verifyEmpty($("#earnestMoney"),"请输入正确的数字") && isNumberTip($("#earnestMoney"),"请输入正确的数字","定金不能超过99999999999");

        //验证办理业务
        var serviceChargeCusCheck = false;
        $.each($("[name='serviceCharge']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"请输入正确的数字") && isNumberTip($(this),"请输入正确的数字","手续费不能超过99999999999");
            if(!nCheck){
                serviceChargeCusCheck = false;
                return false;
            }else{
                serviceChargeCusCheck = true;
            }
        })

        var rateTypeCheck = false;
        $.each($("[name='rateType']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"不能为空");
            if(!nCheck){
                rateTypeCheck = false;
                return false;
            }else{
                rateTypeCheck = true;
            }
        })

        var loanAmountCheck = false;
        $.each($("[name='loanAmount']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"请输入正确的数字") && isNumberTip($(this),"请输入正确的数字","贷款额度不能超过99999999999");
            if(!nCheck){
                loanAmountCheck = false;
                return false;
            }else{
                loanAmountCheck = true;
            }
        })

        var channelIdCheck = false;
        $.each($("[name='channelId']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"不能为空");
            if(!nCheck){
                channelIdCheck = false;
                return false;
            }else{
                channelIdCheck = true;
            }
        })




        //验证借贷人是否有多个借贷人 及身份证号是否重复
        var cardIds = [];
        var cardIdsChecks = false;
        if(cardIdCheck){
            $.each($("[name='cardId']"),function (i,v) {
                var isA = isInArray(cardIds,$(this).val());
                cardIds.push($(this).val());
                if(isA){
                    dggui.dialog.errors("身份证号重复");
                    cardIdsChecks = false;
                    return false;
                }else{
                    cardIdsChecks = true;
                }
            })
        }
        var isSelfFlag=0;
        var isSelfChecks = false;
        if(isSelfCheck){
            $.each($("[name='isSelf']"),function (i,v) {
                if( $(this).val()==1){
                    isSelfFlag = isSelfFlag+1;
                }
            })
            if(isSelfFlag>1){
                dggui.dialog.errors("客户本人只能有一个");
                isSelfChecks = false;
                return false;
            }else{
                isSelfChecks = true;
            }
        }

        //验证成本费

        var subCheck = false;
        $.each($("[name='subjectType']"),function (i,v) {
            var subjectType = $(this).val();
            var subjectNumObj = $(this).parents("tr").find('td').children("input[name='subjectNum']");
            var subjectAmountObj = $(this).parents("tr").find('td div').children("input[name='subjectAmount']");
            var subjectNum = subjectNumObj.val();
            var subjectAmount = subjectAmountObj.val();
            if(checkEmpty(subjectType)||checkEmpty(subjectNum)||checkEmpty(subjectAmount)){
                var subjectTypeCheck = verifyEmpty($(this),"不能为空");
                var subjectNumCheck = verifyEmpty(subjectNumObj,"请输入正确的数字")&&isNumberTip(subjectNumObj,"请输入正确的数字","数量不能超过99999999999");
                var subjectAmountCheck = verifyEmpty(subjectAmountObj,"请输入正确的数字")&&isNumberTip(subjectAmountObj,"请输入正确的数字","价格不能超过99999999999");
                if(subjectTypeCheck&&subjectNumCheck&&subjectAmountCheck){
                    subCheck = true;
                    return;
                }else{
                    subCheck = false;
                    return false;
                };
            }
            if(!checkEmpty(subjectType)&&!checkEmpty(subjectNum)&&!checkEmpty(subjectAmount)){
                subCheck = true;
                return;
            }

        });
        var flowUser =false;
        $.each($("[name='flowUserId']"),function (i,v) {
            var nCheck = verifyEmpty($(this),"不能为空");
            if(!nCheck){
                flowUser = false;
                return false;
            }else{
                flowUser = true;
            }
        })

        //验证通过保存
        var vali = customerNameCheck&&idCardCheck&&sexCheck&&ageCheck&&birthdayCheck&&registeredResidenceCheck
            &&eduBackgroundCheck&&maritalStatusCheck&&childrenNumCheck&&addressCheck&&nameCheck&&lenderStatusCheck
            &&isSelfCheck&&cardIdCheck&&noCheck&&contactMaritalStatusCheck&&contactChildrenNumCheck&&noKnowCheck
            &&relationshipOfCusCheck&&loansAmountCheck&&loansNumCheck&&loansInterestCheck&&loansRateTypeCheck
            &&earnestMoneyCheck&&serviceChargeCusCheck&&rateTypeCheck&&loanAmountCheck&&channelIdCheck
            &&cardIdsChecks&&isSelfChecks&&emailCheck&&subCheck&&flowUser;
        if(vali){
            var customerJson = serializeObject($("#customerJson"));//客户信息信息数组
            var concactJson = serializeObject($("#concactForm"));//借贷人信息数组
            var contractJson = serializeObject($("#contractForm"));//合同约定数组
            contractJson.mortgageAddress = $("#mortgageAddress").val();//抵押物地址值
            var businessJson = serializeObject($("#businessForm"));//办理业务信息数组
            var subjectJson = serializeObject($("#subjectForm"));//成本费数组

            var concactJsonArr = [];
            var businessJsonArr = [];
            var subjectJsonArr = [];
            //封装借贷人
            if($("[name='name']").length>1){
                var cardIds = concactJson.cardId;
                var contactChildrenNums = concactJson.contactChildrenNum;
                var contactMaritalStatuss = concactJson.contactMaritalStatus;
                var isSelfs = concactJson.isSelf;
                var lenderStatuss = concactJson.lenderStatus;
                var names = concactJson.name;
                var nos = concactJson.no;
                var noKnows = concactJson.noKnow;
                var relationshipOfCuss = concactJson.relationshipOfCus;
                for(var i=0;i<cardIds.length;i++){
                    var cJson = {};
                    cJson.cardId = cardIds[i];
                    cJson.contactChildrenNum = contactChildrenNums[i];
                    cJson.contactMaritalStatus = contactMaritalStatuss[i];
                    cJson.isSelf = isSelfs[i];
                    cJson.lenderStatus = lenderStatuss[i];
                    cJson.name = names[i];
                    cJson.no = nos[i];
                    cJson.noKnow = noKnows[i];
                    cJson.relationshipOfCus = relationshipOfCuss[i];
                    concactJsonArr.push(cJson);
                }
            }else {
                concactJsonArr.push(concactJson);
            }

            //封装办理业务
            if($("[name='businessProductCode']").length>1){
                var businessProductCodes = businessJson.businessProductCode;
                var businessProductNames = businessJson.businessProductName;
                var businessTypeCodes = businessJson.businessTypeCode;
                var businessTypeNames = businessJson.businessTypeName;
                var channelIds = businessJson.channelId;
                //var flowUserIds = businessJson.flowUserId;
                var flowUserIds = [];
                //单独处理流程人员
                $.each($("[name='flowUserId']"),function (i,v) {
                    flowUserIds.push($(this).val());
                });
                var loanAmounts = businessJson.loanAmount;
                var orderBusIds = businessJson.orderBusId;
                var orderBusNos = businessJson.orderBusNo;
                var productIds = businessJson.productId;
                var productNames = businessJson.productName;
                var productOrgIds = businessJson.productOrgId;
                var productOrgNames = businessJson.productOrgName;
                var contractNos = businessJson.contractNo;
                var rateTypes = businessJson.rateType;
                var serviceCharges = businessJson.serviceCharge;
                var productGoodsIds = businessJson.productGoodsId;
                var productAttrs = businessJson.productAttr;
                var channelNames = [];

                $.each($("[name='channelId']"),function (i,v) {
                    channelNames.push($(this).select2("data")[0].text);
                });
                var flowUserNames = [];
                $.each($("[name='flowUserId']"),function (i,v) {
                    flowUserNames.push($(this).select2("data")[0].text);
                });
                for(var i=0;i<businessProductCodes.length;i++){
                    var bJson = {};
                    bJson.businessProductCode = businessProductCodes[i];
                    bJson.businessProductName = businessProductNames[i];
                    bJson.businessTypeCode = businessTypeCodes[i];
                    bJson.businessTypeName = businessTypeNames[i];
                    bJson.channelId = channelIds[i];
                    bJson.channelName = channelNames[i];
                    bJson.flowUserId = flowUserIds[i];
                    bJson.flowUserName = flowUserNames[i];
                    bJson.loanAmount = loanAmounts[i];
                    bJson.orderBusId = orderBusIds[i];
                    bJson.orderBusNo = orderBusNos[i];
                    bJson.productId = productIds[i];
                    bJson.productName = productNames[i];
                    bJson.productOrgId = productOrgIds[i];
                    bJson.productOrgName = productOrgNames[i];
                    bJson.contractNo = contractNos[i];
                    bJson.rateType = rateTypes[i];
                    bJson.serviceCharge = serviceCharges[i];
                    bJson.productGoodsId = productGoodsIds[i];
                    bJson.productAttr = productAttrs[i];
                    businessJsonArr.push(bJson);
                }

                var unique = uniqueGoodAndChannel(businessJsonArr);
                if (unique) {
                    dggui.dialog.errors("产品+渠道不唯一，请确认后再次提交")
                    return;

                }

            }else {
                var channelNames = [];
                $.each($("[name='channelId']"),function (i,v) {
                    channelNames.push($(this).select2("data")[0].text);
                });
                var flowUserNames = [];
                $.each($("[name='flowUserId']"),function (i,v) {
                    flowUserNames.push($(this).select2("data")[0].text);
                });
                businessJson.channelName = channelNames[0];
                businessJson.flowUserName = flowUserNames[0];
                businessJsonArr.push(businessJson);
            }


            //封装成本费
            if($("[name='subjectNum']").length>1){
                var subjectNums = subjectJson.subjectNum;
                var subjectAmounts = subjectJson.subjectAmount;
                var subjectTypes = subjectJson.subjectType;
                for(var i=0;i<subjectNums.length;i++){
                    var sJson = {};
                    if(checkEmpty(subjectNums[i])&&checkEmpty(subjectNums[i])&&checkEmpty(subjectTypes[i])){
                        sJson.subjectNum = subjectNums[i];
                        sJson.subjectAmount = subjectAmounts[i];
                        sJson.subjectType = subjectTypes[i];
                        subjectJsonArr.push(sJson);
                    }
                }

            }else {
                if(checkEmpty(subjectJson.subjectAmount)&&checkEmpty(subjectJson.subjectNum)&&checkEmpty(subjectJson.subjectType)){
                    subjectJsonArr.push(subjectJson);
                }
            }
            dggui.dialog.confire("确定保存吗？", "提交审核", function () {
                dggui.dialog.loading();
                $.ajax({
                    type: 'POST',
                    async: true,
                    url: sysInfo.basePath + "/rzsc/api/save_under_order.do",
                    data:{
                        orderNo:$("#orderNo").val(),
                        mortgageAddress:$("#mortgageAddress").val(),
                        loansAmount:$("#loansAmount").val(),
                        loansNum:$("#loansNum").val(),
                        loansRateType:$("#loansRateType").val(),
                        loansInterest:$("#loansInterest").val(),
                        earnestMoney:$("#earnestMoney").val(),
                        contractNo:$("#contractNo").val(),
                        customerJson:JSON.stringify(customerJson),
                        contractJson:JSON.stringify(contractJson),
                        concactJsonArr:JSON.stringify(concactJsonArr),
                        businessJsonArr:JSON.stringify(businessJsonArr),
                        subjectJsonArr:JSON.stringify(subjectJsonArr)
                    },
                    dataType:"json",
                    success: function (result) {
                        dggui.dialog.loading('close');
                        if(result.code==0){
                            dggui.dialog.succeed("提交成功");
                            var returnUrl = result.data;
                            window.location.href = returnUrl;
                        }else {
                            dggui.dialog.errors(result.msg);
                        }
                    }
                })
            })


        }
    }


    function isInArray(arr,value){
        for(var i = 0; i < arr.length; i++){
            if(value === arr[i]){
                return true;
            }
        }
        return false;
    }

    /**
     * 当身份证号变化时，自动计算客户生日、年龄、性别
     */
    function idCardChange(obj,flag) {
        if(checkEmpty(obj.val())){
            var idcard = obj.val();
            if(flag==1){
                if(isCardId(obj) && idcard.length==18){
                    var bir = idcard.substr(6,8);
                    var sex = idcard.substr(16,1);
                    $("[name='birthday']").val(bir.substr(0,4)+"-"+bir.substr(4,2)+"-"+bir.substr(6,2));
                    sex = sex%2 ==0 ? "CMS_SEX_WOMAN":"CMS_SEX_MAN";
                    $("[name='sex']").val(sex);
                    $("[name='age']").val(Number(new Date().getFullYear())-Number(bir.substr(0,4)));
                }

                $("#loansTable").find("tr:gt(1)").each(function(index){
                    if($(this).attr("hidden")=='hidden'){
                        return true;
                    }
                    if(index+1==$("#loansTable").find("tr:gt(1)").length){
                        return true;
                    }
                    var isSelf= $(this).children().find("select[name='isSelf']").find("option:selected").val();//是否是客户本人

                    if(isSelf==1){
                        $(this).children().find("input[name='idCard']").val(idcard);
                    }
                });
            }else if(flag==2){
                var isSelf= $(obj).parents("tr").find("select[name='isSelf']").find("option:selected").val();
                if(isSelf == 1){
                    $("#idCard").val(idcard);
                    if(isIdCardNo(obj) && idcard.length==18){
                        var bir = idcard.substr(6,8);
                        var sex = idcard.substr(16,1);
                        $("[name='birthday']").val(bir.substr(0,4)+"-"+bir.substr(4,2)+"-"+bir.substr(6,2));
                        sex = sex%2 ==0 ? "KHXB_WOMAN":"KHXB_MAN";
                        $("[name='sex']").val(sex);
                        $("[name='age']").val(Number(new Date().getFullYear())-Number(bir.substr(0,4)));
                    }
                }
            }
        }
    }

    function changeCustomerName(obj,flag){
        //客户改订单
        if(flag==1){
            $("#loansTable").find("[name='isSelf']").each(function(index){
                var isSelf= $(this).val();
                if(isSelf==1){
                    $(this).parent().parent().parent().find("input[name='name']").val($(obj).val());
                }

            });

        }
        //订单改客户
        if(flag==2){
            var isSelf= $(obj).parents("tr").find("select[name='isSelf']").find("option:selected").val();
            if(isSelf == 1){
                $("#customerName").val($(obj).val());
            }
        }
    }

    //同步婚姻状况
    function changeMaritalStatus(obj,flag){
        //客户改订单
        if(flag==1){
            $("#loansTable").find("[name='isSelf']").each(function(index){
                var isSelf= $(this).val();
                if(isSelf==1){
                    $(this).parent().parent().parent().find("select[name='contactMaritalStatus']").val($(obj).val());
                }
            });

        }
        //订单改客户
        if(flag==2){
            var isSelf= $(obj).parents("tr").find("select[name='isSelf']").find("option:selected").val();
            if(isSelf == 1){
                $("#maritalStatus").val($(obj).val());
            }
        }
    }
    //同步子女数量
    function changeChildrenNum(obj,flag){
        //客户改订单
        if(flag==1){
            $("#loansTable").find("[name='isSelf']").each(function(index){
                var isSelf= $(this).val();
                if(isSelf==1){
                    $(this).parent().parent().find("input[name='contactChildrenNum']").val($(obj).val());
                }
            });

        }
        //订单改客户
        if(flag==2){
            var isSelf= $(obj).parents("tr").find("select[name='isSelf']").find("option:selected").val();
            if(isSelf == 1){
                $("#childrenNum").val($(obj).val());
            }
        }
    }


    function changeState(obj,flag){
        if(1 == flag){
            var lenderStatus= $(obj).parents("tr").find("select[name='lenderStatus']").find("option:selected").val();
            if("0" == lenderStatus){
                $(obj).parents("tr").find("select[name='relationshipOfCus']").val("ORF_JDRGX_1");
            }else {
                $(obj).parents("tr").find("select[name='relationshipOfCus']").val("");
            }
        }else if(2 == flag){
            var relationshipOfCus =  $(obj).parents("tr").find("select[name='relationshipOfCus']").find("option:selected").val();
            if("ORF_JDRGX_1" == relationshipOfCus){
                $(obj).parents("tr").find("select[name='lenderStatus']").val(0);
            }else{
                $(obj).parents("tr").find("select[name='lenderStatus']").val(1);
            }
        }

    }

    function getCustomerMessage(obj) {
        var isSelf= $(obj).parents("tr").find("select[name='isSelf']").find("option:selected").val();
        if("1"==isSelf){
            $(obj).parents("tr").find("input[name='name']").val($("#customerName").val());
            $(obj).parents("tr").find("input[name='cardId']").val($("#idCard").val());
            $(obj).parents("tr").find("input[name='no']").val($("#contactPhoneId").val());
            $(obj).parents("tr").find("select[name='contactMaritalStatus']").val($("#maritalStatus").val());
            $(obj).parents("tr").find("input[name='contactChildrenNum']").val($("#childrenNum").val());
        }
    }

</script>
</html>
